﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class PlayerHealth : MonoBehaviour
{
    private Animator anim;
    public Heart healthManager;

    [Header("主角血量")]
    public int healthPoint;

    [Header("受伤后需要闪烁的图片")]
    public SpriteRenderer twinkle;
    [Header("无敌持续时间")]
    public float invincibleTime;
    [Header("无敌的人物")]
    public GameObject Player;

    private float timer;
    private bool invincible;

    void Awake()
    {
        healthManager.Initiate(healthPoint);
    }

    //Use this for initialization
    void Start()
    {

    }

    //Update is called once per frame
    void Update()
    {
        //死亡
        if (healthPoint <= 0)
        {
            //死亡时无闪动效果
            //invincible = false;
            // 角色死亡动画
            //animator.SetTrigger("die");
        }
        Twinkle();
    }
    /// <summary>
    /// 增加血量
    /// </summary>
    /// <param name="value">血量值</param>
    public void IncreaseHP(int value)
    {
        healthPoint += 1;
        healthManager.Add();//调用血量
    }

    public void ReduceBlood(int value)
    {
        // 减少角色健康
        healthPoint -= 1;
        healthManager.Sub();
        invincible = true;
    }
    void Twinkle()
    {
        // 持续闪烁时间计算
        if (invincible)
        {
            timer += Time.deltaTime;
            if (timer >= invincibleTime)
            {
                twinkle.enabled = true;

                invincible = false;
                timer = 0;
            }
            else
            {
                //将计时器中时间取余，如果余大于0.1则图片消失
                float remainder = timer % 0.3f;
                twinkle.enabled = remainder > 0.1f;
                //Debug.Log(remainder);
            }
            //无敌状态实现
            Player.layer = LayerMask.NameToLayer("Invincible");
        }
        else
        {
            //无敌状态消失
            Player.layer = LayerMask.NameToLayer("Player");
        }
    }
}
